<template>
  <div class="table-box">
    <table>
      <thead>
        <tr>
          <th colspan="2">时 间</th>
          <th>周 一</th>
          <th>周 二</th>
          <th>周 三</th>
          <th>周 四</th>
          <th>周 五</th>
          <th>周 六</th>
          <th>周 日</th>
        </tr>
      </thead>
      <tbody>
        <template v-for="timeItem in dayTimeList" :key="timeItem.dayTime">
          <tr>
            <!-- 上午下午晚上 -->
            <th :rowspan="timeItem.rowList.length + 1">{{ timeItem.dayTime }}</th>
          </tr>
          <tr v-for="rowItem in timeItem.rowList" :key="rowItem.orderNum">
            <th>
              <!-- 第几节课 -->
              <article>{{ courseOrder(rowItem.orderNum) }}</article>
              <span>{{ rowItem.time }}</span>
            </th>
            <!-- 课程 -->
            <td v-for="colNum in 7" :key="colNum" :class="tdClass" :style="tdStyle" @click.stop="onTdCilck(rowItem.orderNum, colNum)" ref="tdRef">
              <template v-for="course in courseData" :key="course.name">
                <el-popover
                  v-if="findThisCourse(course, rowItem.orderNum, colNum) && isShowPopver"
                  :hide-after="200"
                  :show-after="0"
                  popper-class="popper"
                >
                  <template #reference>
                    <section class="course-box" :style="boxStyle(course)" @click.stop="onCourseClick(course, rowItem.orderNum, colNum)">
                      <div :class="courseClass" :style="courseStyle(course)" @mouseover="onShowDetail(course)" ref="courseRef">
                        <article>{{ course.courseName }}</article>
                        <aside>{{ course.tchName }}</aside>
                      </div>
                    </section>
                  </template>
                  <div class="popover-content">
                    <article>{{ popverCourseData?.courseName }}</article>
                    <span>{{ popverCourseData?.tchName }}</span>
                    <span>{{ popverCourseData?.place }}</span>
                  </div>
                </el-popover>
                <section
                  class="course-box"
                  :style="boxStyle(course)"
                  @click.stop="onCourseClick(course, rowItem.orderNum, colNum)"
                  v-if="findThisCourse(course, rowItem.orderNum, colNum) && !isShowPopver"
                >
                  <div :class="courseClass" :style="courseStyle(course)" ref="courseRef">
                    <article>{{ course.courseName }}</article>
                    <aside>{{ course.tchName }}</aside>
                  </div>
                </section>
              </template>
            </td>
          </tr>
        </template>
      </tbody>
    </table>
  </div>
</template>

<script lang="ts">
export enum courseTableType {
  add = 'add',
  edit = 'edit',
  delete = 'delete',
  default = '',
}
</script>
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { IActiveCourseList, IActiveTdList, ICourseTable } from '../../type';

interface IProps {
  data: ICourseTable[];
  openType: courseTableType;
  // isEdit?: boolean;
}

const props = defineProps<IProps>();
let activeTdList = [] as IActiveTdList[];
let activeCourseList = [] as IActiveCourseList[];
const tdRef = ref();
const courseRef = ref();
const popverCourseData = ref<ICourseTable>();

const viewOrderd = (courseData: ICourseTable[]) => {
  const rowOrderdList = courseData.sort((a: any, b: any) => a.orderNum - b.orderNum);

  let currentRowNum: number;
  let usedRows = [] as number[];
  let allOrderdList = [];
  for (let i = 0; i < rowOrderdList.length; i++) {
    currentRowNum = rowOrderdList[i].orderNum;

    let flag = false;
    for (const usedRow of usedRows) {
      if (currentRowNum === usedRow) {
        flag = true;
        break;
      }
    }
    if (flag) continue;
    else usedRows.push(currentRowNum);

    let sameRowItems = rowOrderdList.filter((item: ICourseTable) => {
      if (item.orderNum === currentRowNum) return item;
    });
    sameRowItems.sort((a: any, b: any) => a.weekDay - b.weekDay);

    allOrderdList.push(...sameRowItems);
  }
  return allOrderdList;
};

//循环的课程数据
//courseData需要按行排序后每行再按列排序，否则通过ref拿到的课程dom数组下标，与courseData下标不对应。导致高亮错乱问题
const courseData = ref<ICourseTable[]>(viewOrderd(props.data));

watch(
  () => props.data,
  newValue => {
    courseData.value = viewOrderd(newValue);
  }
);

const tdStyle = computed(() => {
  // if (props.openType === 'add') return 'editTd';
  // else return '';
  return '';
});

const tdClass = computed(() => {
  if (props.openType === 'add') return 'editTd';
  else return '';
});

const emit = defineEmits(['onTdClick', 'onCourseClick']);
const onTdCilck = (rowNum: number, colNum: number) => {
  if (props.openType !== 'add') return;

  const currentTd = tdRef.value[(rowNum - 1) * 7 + colNum - 1];
  const className = currentTd.className;

  //改变样式
  if (className === 'editTd') currentTd.className = 'activeTd';
  else if (className === 'activeTd') currentTd.className = 'editTd';

  //给activeTdList增加或删除该td
  let uniqueTd = true;
  for (let index = 0; index < activeTdList.length; index++) {
    const item = activeTdList[index];
    if (rowNum === item.rowNum && colNum === item.colNum) {
      activeTdList.splice(index, 1);
      uniqueTd = false;
      break;
    }
  }
  if (uniqueTd) activeTdList.push({ rowNum, colNum });
  // console.log(activeTdList);

  emit('onTdClick', activeTdList);
};

const onShowDetail = (course: ICourseTable) => {
  setTimeout(() => {
    popverCourseData.value = course;
  }, 200);
};

const isShowPopver = computed(() => {
  if (props.openType === '') return true;
  else return false;
});

const courseOrder = computed(() => (orderNum: number) => {
  let stringOrder = '';
  switch (orderNum) {
    case 1:
      stringOrder = '一';
      break;
    case 2:
      stringOrder = '二';
      break;
    case 3:
      stringOrder = '三';
      break;
    case 4:
      stringOrder = '四';
      break;
    case 5:
      stringOrder = '五';
      break;
    case 6:
      stringOrder = '六';
      break;
    case 7:
      stringOrder = '七';
      break;
    case 8:
      stringOrder = '八';
      break;
    case 9:
      stringOrder = '九';
      break;
    case 10:
      stringOrder = '十';
      break;
    case 11:
      stringOrder = '十一';
      break;
    case 12:
      stringOrder = '十二';
      break;
    default:
      break;
  }
  return `第${stringOrder}节`;
});

const findThisCourse = computed(() => (course: any, rowIndex: number, colNum: number) => {
  return course.orderNum === rowIndex && course.weekDay === colNum;
});

const boxStyle = computed(() => (course: ICourseTable) => {
  return `height:${course.smallCount * 100}%;`;
  //能进该计算属性，说明course已是位置正确的课程
  //课程延申的高度和背景色(分是否为编辑状态)
  // if (props.openType === 'add') return `height:${course.smallCount * 100 - 20}%;`;
  // else if (props.openType === 'edit' || props.openType === 'delete') return `height:${course.height * 100 - 20}%;background-color: cadetblue;`;
  // else return `height:${course.smallCount * 100 - 20}%;`;
});

const courseStyle = computed(() => (course: ICourseTable) => {
  //能进该计算属性，说明course已是位置正确的课程
  //课程延申的高度和背景色(分是否为编辑状态)
  // if (props.openType === 'add') return `height:${course.smallCount * 100 - 20}%;`;
  if (props.openType !== 'add') return `background-color:${course.color};`;
});

const courseClass = computed(() => {
  if (props.openType === 'add') return 'addCourse';
  else return 'course';
});

const onCourseClick = (course: ICourseTable, rowNum: number, colNum: number) => {
  if (!(props.openType === 'edit' || props.openType === 'delete')) return;

  changeCourseActiveClass(rowNum, colNum);

  if (props.openType === 'edit') {
    if (activeCourseList.length !== 0) {
      if (activeCourseList[0].rowNum === rowNum && activeCourseList[0].colNum === colNum) {
        activeCourseList = [];
      } else {
        changeCourseActiveClass(activeCourseList[0].rowNum, activeCourseList[0].colNum);
        activeCourseList = [];
        activeCourseList.push({ rowNum, colNum, course });
      }
    } else {
      activeCourseList.push({ rowNum, colNum, course });
    }
  }

  if (props.openType === 'delete') {
    //给activeCourseList增加或删除(多选)
    let uniqueTd = true;
    for (let index = 0; index < activeCourseList.length; index++) {
      const item = activeCourseList[index];
      if (rowNum === item.rowNum && colNum === item.colNum) {
        activeCourseList.splice(index, 1);
        uniqueTd = false;
        break;
      }
    }
    if (uniqueTd) activeCourseList.push({ rowNum, colNum, course });
  }
  // console.log(activeCourseList);

  emit('onCourseClick', activeCourseList);
};

const changeCourseActiveClass = (rowNum: number, colNum: number) => {
  let currentIndex = 0;
  for (const index in courseData.value) {
    const item = courseData.value[index];
    if (item.orderNum === rowNum && item.weekDay === colNum) {
      currentIndex = Number(index);
      break;
    }
  }

  const currentCourse = courseRef.value[currentIndex];
  const className = currentCourse.className;

  //没有直接用currentCourse.style.backgroundColor是因为，鼠标离开后active燕娥就丢失了
  //因为click的同时有hover效果的popver组件，所以有附加className
  // if (className === 'course el-tooltip__trigger el-tooltip__trigger')
  //   currentCourse.className = 'activeCourse el-tooltip__trigger el-tooltip__trigger';
  // else if (className === 'activeCourse el-tooltip__trigger el-tooltip__trigger')
  //   currentCourse.className = 'course el-tooltip__trigger el-tooltip__trigger';

  if (className === 'course') currentCourse.className = 'activeCourse';
  else if (className === 'activeCourse') currentCourse.className = 'course';
};

const dayTimeList = [
  {
    dayTime: '上午',
    rowList: [
      {
        orderNum: 1,
        time: '08:00 ~ 08:45',
      },
      {
        orderNum: 2,
        time: '08:55 ~ 09:40',
      },
      {
        orderNum: 3,
        time: '10:05 ~ 10:50',
      },
      {
        orderNum: 4,
        time: '11:00 ~ 11:45',
      },
    ],
  },
  {
    dayTime: '下午',
    rowList: [
      {
        orderNum: 5,
        time: '14:00 ~ 14:45',
      },
      {
        orderNum: 6,
        time: '14:55 ~ 15:40',
      },
      {
        orderNum: 7,
        time: '16:05 ~ 16:50',
      },
      {
        orderNum: 8,
        time: '17:00 ~ 17:45',
      },
    ],
  },
  {
    dayTime: '晚上',
    rowList: [
      {
        orderNum: 9,
        time: '19:00 ~ 19:45',
      },
      {
        orderNum: 10,
        time: '19:55 ~ 20:40',
      },
      {
        orderNum: 11,
        time: '20:50 ~ 21:35',
      },
    ],
  },
];

// defineExpose({
//   isEdit,
// });
</script>

<style lang="scss" scoped>
.course-box {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 1;
  padding: 5%;
}
// .scourse-table {
//   height: 100%;
.table-box {
  height: 100%;

  .white-space {
    height: 3%;
  }

  .course,
  .addCourse,
  .activeCourse {
    height: 100%;
    display: flex;
    justify-content: space-around;
    align-items: center;
    flex-direction: column;
    border-radius: 8px;
    transition: all 0.3s;
    article {
      font-size: 18px;
    }
  }
  .course:hover {
    cursor: pointer;
    transition: all 0.3s;
    // transform: translateY(-6px);
    box-shadow: 0 4px 12px 8px rgba(0, 0, 0, 0.1);
  }
  .addCourse {
    background-color: #bfc4cc;
    cursor: not-allowed;
  }
  .activeCourse {
    cursor: pointer;
    // border: 2px solid var(--border-color);
    background-color: rgb(230, 183, 96) !important;
  }
}
table {
  width: 100%;
  height: 100%;
  border-spacing: 0;
  border-left: 1px solid var(--border-color);
  border-top: 1px solid var(--border-color);
  th,
  td {
    border-right: 1px solid var(--border-color);
    border-bottom: 1px solid var(--border-color);
    text-align: center;
  }
  .editTd {
    cursor: pointer;
  }
  .activeTd {
    cursor: pointer;
    background-color: rgb(230, 183, 96);
  }
  thead {
    th {
      height: 50px;
      line-height: 50px;
    }
  }
  tbody {
    td {
      position: relative;
    }
  }
}
// }

.popover-content {
  display: flex;
  justify-content: space-around;
  align-items: center;
  flex-direction: column;
  height: 100px;
  color: var(--font-color);
  article {
    font-size: 18px;
  }
}
</style>
